﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler
{
    public class GetMenuCommendHandlers : IRequestHandler<GetMenuCommends, APIResult<List<ChildrenMenusDto>>>
    {

        private readonly IBaseRepository<Menu> menuRepository;
        private readonly IMapper mapper;

        public GetMenuCommendHandlers(IBaseRepository<Menu> menuRepository, IMapper mapper)
        {
            this.menuRepository = menuRepository;
            this.mapper = mapper;
        }

        /// <summary>
        /// 获取菜单树状图
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<APIResult<List<ChildrenMenusDto>>> Handle(GetMenuCommends request, CancellationToken cancellationToken)
        {
            APIResult<List<ChildrenMenusDto>> result = new APIResult<List<ChildrenMenusDto>>();
            result.Code = APIEnum.查询成功;
            result.Msg=APIEnum.查询成功.ToString();

             result.data = getChildrenMenus(0);


            return Task.FromResult(result);
        }

        public List<ChildrenMenusDto> getChildrenMenus(int ParentId)
        {
            var parents = menuRepository.GetAll().Where(x => x.ParentMenuId == ParentId);
            var ParentDtos=mapper.Map<List<ChildrenMenusDto>>(parents);
            foreach (var item in ParentDtos)
            {
                item.Children = getChildrenMenus(item.MenuId);
            }
            return ParentDtos;
        }

    }
}
